<template>
  <div class="home">
    <!---------------头部搜索框---------------->
    <div class="header-wrapper">
      <div class="header-content">
        <div class="logo">Fehead</div>
        <input type="text" placeholder="请输入订单目的地" @focus="focused = true" @keyup="focused = false" @keyup.enter="searchByDestination" v-model="desInput"></input>
        <span class="iconfont icon-yonghu" @click="toMe()"></span>
      </div>
      <div class="tag-advice" v-if="focused">
        <div class="tag" v-for="item in expressPoints"><div @click="clickTag(item)">{{item.deliveryPoint}}</div></div>
      </div>
    </div>
    <!--------------订单列表------------------>
<!--    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">-->
    <div class="lists-wrapper">
      <mescroll-vue ref="mescroll" :down="mescrollDown" :up="mescrollUp" @init="mescrollInit">
        <div class="lists" v-for="(list,index) in lists" @click="forMore_receiver(index)">
          <div class="fee-wrapper">
            {{list.fee}}
          </div>
          <div class="other-wrapper">
            <div class="deliveryInfo">
              <div class="deliveryPoint">
                <div><b>{{list.deliveryPoint.area}}</b></div>
                <div><b>{{list.deliveryPoint.deliveryPoint}}</b></div>
              </div>
                <div class="sponsor">发起人：{{list.displayName}}</div>
              <div class="deadline">截止时间：{{list.deadline | formatDate}}</div>
            </div>
            <div class="destination">送至：{{list.destination}}</div>
            <div class="timeInfo">
              发布时间：{{list.updateTime | formatDate}}
            </div>
          </div>
        </div>
      </mescroll-vue>
    </div>
<!--    </van-pull-refresh>-->
    <div class="loading" v-if="pageLoading">
      <van-loading type="spinner" color="#1DA57A" size="24px" vertical>加载中...</van-loading>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Provide } from 'vue-property-decorator';
import {Toast} from 'vant';
//引入上拉加载、下拉刷新组件
import MescrollVue from 'mescroll.js/mescroll.vue'

@Component({
  components: {
    MescrollVue
  },
})
export default class Home extends Vue {
  @Provide() page:number = 1;  // 请求订单的页码
  @Provide() expressPoints:string[] = [];
  @Provide() desInput:string = '';
  @Provide() isLoading:boolean = false;
  @Provide() focused:boolean = false;
  @Provide() pageLoading:boolean = true;
  // 订单列表
  @Provide() lists:Object[] = [];

  // 上拉刷新，下拉加载组件
  @Provide() mescroll:any = null; // mescroll实例对象
  @Provide() mescrollDown:object = {};
  @Provide() mescrollUp:object = {
    callback: this.upCallback, // 上拉回调,此处可简写; 相当于 callback: function (page, mescroll) { getListData(page); }
    page: {
      num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
      size: 6 // 每页数据的数量
    },
    lazyLoad: {
      use: true // 是否开启懒加载,默认false
    },
    noMoreSize: 5,
    toTop: {
      //回到顶部按钮
      src: "", //图片路径,默认null,支持网络图
      offset: 600 //列表滚动600px才显示回到顶部按钮
    },
  };

  // mescroll组件初始化的回调,可获取到mescroll对象
  mescrollInit(mescroll: any) {
    this.mescroll = mescroll;  // 如果this.mescroll对象没有使用到,则mescrollInit可以不用配置
  }

  // 上拉回调 page = {num:1, size:10}; num:当前页 ,默认从1开始; size:每页数据条数,默认10
  upCallback(page: { num: number; size: any; }, mescroll: { endSuccess: (arg0: number) => void; endErr: { (): void; (): void; }; }) {
    let that = this;
    (this as any).$axios
      .get((this as any).baseUrl + '/api/v1.0/SUSTDelivery/view/order/lists/0', {
        params: {
          page: page.num,
          pageSize: page.size
        }
      })
      .then((res: any) => {
        // console.log("订单", res);
        if (res.data.status === "success") {
          this.pageLoading = false;
          let data_lists = [];
          // 将列表中的费用改成'X元'格式
          for ( let i: number = 0; i < this.lists.length; i ++) {
            (this as any).lists[i].fee = parseInt((this as any).lists[i].fee) + '元';
          }
          // console.info("分页数据",res.data.data);
          if (res.data.data.length > 0) {   // 当下一页有数据时
            data_lists = res.data.data;
            let data = page.num === 1 ? [] : that.lists;
            // console.info("data",data);
            data.push(...data_lists);
            that.lists = data;
          }
          // 数据渲染成功后,隐藏下拉刷新的状态
          this.$nextTick(() => {
            mescroll.endSuccess(that.lists.length);
          });
          // 获取快递点信息
          (this as any).$axios
            .get((this as any).baseUrl + '/api/v1.0/SUSTDelivery/view/order/lists/delivery')
            .then((res: any) => {
              // console.info("tags",res);
              if (res.data.status === "success") {
                this.expressPoints = res.data.data;
                this.$store.commit('SET_DELIVERYPOINTS', this.expressPoints);
              } else {
                Toast.fail(res.data.data.errorMsg);
              }
            })
            .catch((err: any) => {
              Toast.fail("网络连接错误");
            })
        } else {
          Toast.fail(res.data.data.errorMsg);
        }
      })
      .catch((error: any) => {
        mescroll.endErr();
        this.pageLoading = false;
        console.error("errRes", error);
      });
  }
  beforeRouteEnter(to: any, from: any, next: (arg0: (vm: any) => void) => void) { // 如果没有配置回到顶部按钮或isBounce,则beforeRouteEnter不用写
    next(vm => {
      // 找到当前mescroll的ref,调用子组件mescroll-vue的beforeRouteEnter方法
      vm.$refs.mescroll && vm.$refs.mescroll.beforeRouteEnter() // 进入路由时,滚动到原来的列表位置,恢复回到顶部按钮和isBounce的配置
    })
  }
  beforeRouteLeave(to: any, from: any, next: () => void) { // 如果没有配置回到顶部按钮或isBounce,则beforeRouteLeave不用写
    // 找到当前mescroll的ref,调用子组件mescroll-vue的beforeRouteEnter方法
    this.$refs.mescroll && this.$refs.mescroll.beforeRouteLeave(); // 退出路由时,记录列表滚动的位置,隐藏回到顶部按钮和isBounce的配置
    next()
  }

  // 快递点搜索
  private clickTag(point: any): void {
    this.pageLoading = true;
    this.focused = false;
    // console.log(point);
    (this as any).$axios
      .get((this as any).baseUrl + `/api/v1.0/SUSTDelivery/view/order/lists/${point.id}`,{
        params:{
          page: 1,
          pageSize: 10
        }
      })
        .then((res: any) => {
          console.log(res);
          this.pageLoading = false;
          if (res.data.status === 'success') {
            this.lists = res.data.data;
          } else {
            Toast.fail(res.data.data.errorMsg);
          }
        })
        .catch((err: any) => {
          this.pageLoading = false;
          Toast.fail("网络连接错误");
        })
  }

  // 根据目的地搜索订单
  private searchByDestination(): void {
    // console.info(this.desInput);
    this.pageLoading = true;
    let params = new URLSearchParams();
    params.append("search",this.desInput);
    params.append("page","1");
    params.append("pagesize","10");
    (this as any).$axios
      .post((this as any).baseUrl + '/api/v1.0/SUSTDelivery/view/order/lists',params)
          .then((res: any) => {
            console.info("des",res);
            this.pageLoading = false;
            if (res.data.status === "success") {
              this.lists = res.data.data;
            } else {
              Toast.fail(res.data.data.errorMsg);
            }
          })
          .catch((err: any) => {
            this.pageLoading = false;
            Toast.fail("网络连接错误");
          })
  }

  private forMore_receiver(index: number): void{
    sessionStorage.setItem("list_id",(this as any).lists[index].id);  //存储当前点击订单的id
    this.$store.commit('SET_LISTID',(this as any).lists[index].id);
    (this as any).$router.push({
        name:'forMore',
        params:{
          role:"receiver"
        }
      })
  }
  // 进入个人中心
   private toMe(): void {
    this.$router.push({path: '/aboutMe'});
  }
}
</script>

<style lang="less" scoped>
  @mainColor:#1DA57A;
  .home {
    width: 100%;
    .header-wrapper {
      z-index: 1000;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: fixed;
      top: 0;
      background: @mainColor;
      width: 100%;
      padding-top: 1.6%;
      padding-bottom: 1.6%;
      .header-content {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        .logo {
          width: 22%;
          text-align: center;
          color: white;
        };
        input {
          border: 0;
          border-radius: .4rem;
          width: 63%;
          padding-left: 1rem;
          outline: none;
          font-size: .92rem;
          padding-top: 1%;
          padding-bottom: 1%;
          &:focus{
            border: 1px solid tint(@mainColor,80%);
          }
        }
        .icon-yonghu{
          color: white;
          font-size: 1.86rem;
          width: 15%;
          text-align: center;
          &:active{
            color: lighten(@mainColor,50%);
          }
        }
      }
      .tag-advice {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        margin: .2rem auto 0 auto;
        width: 92%;
        text-align: center;
        .tag {
          margin: .4rem .3rem;
          background: white;
          color: @mainColor;
          border-radius: .4rem;
          padding: .2rem .3rem;
          &:active {
            background-color: lighten(@mainColor,50%);
          }
        }
      }
    }
    .lists-wrapper{
      margin-top: 15%;
      min-height: 100vh;
      .lists {
        display: flex;
        flex-direction: row;
        margin-top: 1rem;
        padding: 0 1rem 0 0;
        .fee-wrapper{
          display: flex;
          flex-direction: column;
          justify-content: center;
          width: 18%;
          text-align: center;
          font-size: 1.4rem;
          margin-right: 5%;
          background-color: lighten(@mainColor,5%);
          color: white;
          font-weight: bold;
        }
        .other-wrapper{
          margin-top: 1rem;
          margin-bottom: 1rem;
          .deliveryPoint{
            display: flex;
            flex-direction: column;
          }
          .destination{
            font-size: .92rem;
          }
        }
      }
    }
  }
</style>
